<style>
.page {
  text-align: center;
  margin-top: 7px;
}
.page1 {
  text-align: center;
  margin-top: 15px;
  overflow-x: hidden;
  overflow-y: auto;
  table-layout: fixed;
}
.ivu-table-overflowX {
  overflow-x: hidden;
}
.demo-drawer-profile {
  font-size: 14px;
}
.demo-drawer-profile .ivu-col {
  margin-bottom: 12px;
}
.myrole {
  margin-left: 10px;
}
.in1 {
  margin-left: 7px;
}
.in2 {
  margin-left: 14px;
}
</style>
<template>
  <div>
    <Breadcrumb>
      <BreadcrumbItem to="/main/myInfo">
        <e-icon icon-name="el-icon-s-home"></e-icon>主页
      </BreadcrumbItem>
      <BreadcrumbItem>
        <e-icon icon-name="fa fa-sitemap"></e-icon>职工管理
      </BreadcrumbItem>
      <BreadcrumbItem>员工管理 </BreadcrumbItem>
    </Breadcrumb>

    <Divider />

    <Button type="primary" icon="md-person-add" @click="open">添加员工</Button>

    <Modal
      ref="modal1"
      :loading="isLoading"
      v-model="modal1"
      title="添加员工"
      @on-ok="addEmp('empPO')"
      @on-cancel="cancel"
    >
      <Form ref="empPO" :model="empPO" :rules="ruleValidate" :label-width="80">
        <FormItem label="员工代码" prop="code">
          <Input
            clearable
            v-model="empPO.code"
            placeholder="请输入员工代码"
          ></Input>
        </FormItem>
        <FormItem label="员工名称" prop="name">
          <Input
            clearable
            v-model="empPO.name"
            placeholder="请输入员工名称"
          ></Input>
        </FormItem>
        <FormItem label="员工性别" prop="sex">
          <RadioGroup v-model="empPO.sex">
            <Radio label="0" border> 女 </Radio>
            <Radio label="1" border> 男 </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="手机号码" prop="mobile">
          <Input
            clearable
            v-model="empPO.mobile"
            placeholder="请输入员工号码"
          ></Input>
        </FormItem>
        <FormItem label="员工部门" prop="deptId">
          <el-select
            v-model="empPO.deptId"
            clearable
            placeholder="请选择"
            @clear="handleClearDept"
            ref="selectUpResId1"
            style="width: 410px"
          >
            <el-option hidden :label="deptName" v-model="empPO.deptId">
            </el-option>
            <el-tree
              :data="data2"
              :props="defaultProps"
              :expand-on-click-node="false"
              :check-on-click-node="true"
              @node-click="handleNodeClick"
            >
            </el-tree>
          </el-select>
        </FormItem>
        <FormItem label="员工账号" prop="userId">
          <Select
            v-model="empPO.userId"
            clearable
            placeholder="请选择员工账号"
            @clear="handleClearUser"
            style="width: 410px"
          >
            <Option v-for="item in selectUser" :key="item.id" :value="item.id">
              {{ item.value }}
            </Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      ref="modal2"
      :loading="isLoading"
      v-model="modal2"
      title="修改员工"
      @on-ok="updateEmp('empPO2')"
      @on-cancel="cancel"
    >
      <Form
        ref="empPO2"
        :model="empPO"
        :rules="ruleValidate2"
        :label-width="80"
      >
        <FormItem label="员工代码" prop="code">
          <Input
            clearable
            v-model="empPO.code"
            placeholder="请输入员工代码"
          ></Input>
        </FormItem>
        <FormItem label="员工名称" prop="name">
          <Input
            clearable
            v-model="empPO.name"
            placeholder="请输入员工名称"
          ></Input>
        </FormItem>
        <FormItem label="员工性别" prop="sex">
          <RadioGroup v-model="empPO.sex">
            <Radio :label="0" border>女</Radio>
            <Radio :label="1" border>男</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="手机号码" prop="mobile">
          <Input
            clearable
            v-model="empPO.mobile"
            placeholder="请输入员工号码"
          ></Input>
        </FormItem>
        <FormItem label="员工部门" prop="deptId">
          <el-select
            v-model="empPO.deptId"
            clearable
            placeholder="请选择"
            @clear="handleClearDept3"
            ref="selectUpResId2"
            style="width: 410px"
          >
            <el-option
              hidden
              key="upResId"
              :label="empPO.deptName"
              v-model="empPO.deptId"
            >
            </el-option>
            <el-tree
              :data="data2"
              :props="defaultProps"
              :expand-on-click-node="false"
              :check-on-click-node="true"
              @node-click="handleNodeClick2"
            >
            </el-tree>
          </el-select>
        </FormItem>
        <FormItem label="员工账号" prop="userId">
          <Select
            v-model="empPO.userId"
            clearable
            placeholder="请选择"
            @clear="handleClearUser"
            style="width: 410px"
          >
            <Option
              v-for="item in selectUser"
              :label="item.value"
              :value="item.id"
              :key="item.id"
            >
            </Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>

    <Input
      class="in1"
      clearable
      v-model="empQo.code"
      placeholder="请输入员工代码"
      style="width: 200px"
    />
    <Input
      class="in1"
      clearable
      v-model="empQo.name"
      placeholder="请输入员工姓名"
      style="width: 200px"
    />
    <Select
      class="in1"
      v-model="empQo.sex"
      clearable
      style="width: 200px"
      placeholder="请选择员工性别"
    >
      <Option value="0">男</Option>
      <Option value="1">女</Option>
    </Select>
    <el-select
      class="in1"
      v-model="empQo.deptId"
      clearable
      size="small"
      style="width: 200px; height: 30px"
      placeholder="请选择员工部门"
      @clear="handleClearDept2"
      ref="selectUpResId3"
    >
      <el-option hidden :label="deptName2" v-model="empQo.deptId"> </el-option>
      <el-tree
        :data="data2"
        :props="defaultProps"
        :expand-on-click-node="false"
        :check-on-click-node="true"
        @node-click="handleNodeClick3"
      >
      </el-tree>
    </el-select>
    <Button class="in1" type="primary" icon="ios-search" @click="selectEmp"
      >搜索</Button
    >
    <Button class="in1" icon="md-close" @click="reset">清除</Button>
    <Table
      style="width: 100%"
      context-menu
      show-context-menu
      class="page1"
      ref="selection"
      border
      :columns="columns1"
      :data="data.records"
      @on-selection-change="checkEmp"
      @on-contextmenu="handleContextMenu"
      :loading="loading"
    >
      <template slot="contextMenu">
        <DropdownItem @click.native="handleContextMenuEdit">修改</DropdownItem>
        <DropdownItem
          @click.native="handleContextMenuDelete"
          style="color: #ed4014"
          >删除</DropdownItem
        >
      </template>
    </Table>
    <Button
      class="page1"
      type="error"
      ghost
      @click="ifDeleteAll"
      icon="ios-trash"
      >删除所选</Button
    >
    <Page
      class="page"
      :total="data.total"
      :current="data.current"
      :page-size="6"
      :page-size-opts="pagesizeopts"
      @on-change="changePage"
      @on-page-size-change="sizeChange"
      show-elevator
      show-total
      show-sizer
    />
    <Modal v-model="value4" width="450">
      <p slot="header">
        <Icon type="ios-information-circle"></Icon>
        <span>员工详情信息</span>
      </p>
    </Modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //表格加载
      loading: true,
      //树形组件需要的数据对应
      defaultProps: {
        children: "children",
        label: "name",
      },
      deptName: "",
      deptName2: "",
      //部门下拉框的数据
      data2: [],
      //员工详情
      details: {},
      //每页展示条数
      pagesizeopts: [6, 10, 15, 20],
      //存放查询员工empVo的信息
      data: {},
      //数据库用户的集合
      selectUser: [],
      //查询员工的查询条件
      empQo: {
        pageSize: 6,
        pageIndex: 1,
      },
      //添加员工确定按钮的一直加载，添加信息不符合要求时不会关闭弹窗
      isLoading: true,
      //添加员工->是否打开弹窗
      modal1: false,
      //修改员工->否打开弹窗
      modal2: false,
      //添加员工时存储员工的信息
      empPO: {},
      //存储多选时员工id
      empIdList: [],
      //员工详情页面的style
      pStyle: {
        fontSize: "16px",
        color: "rgba(0,0,0,0.85)",
        lineHeight: "24px",
        display: "block",
        marginBottom: "16px",
      },
      //是否显示员工详情页
      value4: false,
      //右键表格的行数
      contextLine: "",
      //添加员工时的表单验证
      ruleValidate: {
        code: [
          { required: true, message: "员工代码不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "员工姓名不能为空", trigger: "blur" },
        ],
        sex: [
          {
            required: true,
            message: "员工性别不能为空",
            trigger: "blur",
          },
        ],
        // deptId: [
        //   {
        //     required: true,
        //     message: "员工部门不能为空",
        //     trigger: "blur",
        //   },
        // ],
        // userId: [
        //   {
        //     required: true,
        //     message: "员工所属用户不能为空",
        //     trigger: "blur",
        //   },
        // ],
      },
      //修改员工时的表单验证
      ruleValidate2: {
        code: [
          { required: true, message: "员工代码不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "员工姓名不能为空", trigger: "blur" },
        ],
        // sex: [
        //   {
        //     required: true,
        //     message: "员工性别不能为空",
        //     trigger: "blur",
        //   },
        // ],
        // deptId: [
        //   {
        //     required: true,
        //     message: "员工部门不能为空",
        //     trigger: "blur",
        //   },
        // ],
        // userId: [
        //   {
        //     required: true,
        //     message: "员工所属用户不能为空",
        //     trigger: "blur",
        //   },
        // ],
      },
      //员工的表格
      columns1: [
        {
          width: 60,
          type: "selection",
        },
        {
          title: "ID",
          key: "id",
          width: 60,
        },
        {
          title: "员工代码",
          key: "code",
          width: 200,
        },
        {
          title: "员工名称",
          key: "name",
          width: 200,
        },
        {
          title: "所属部门",
          key: "deptName",
          width: 220,
        },
        {
          title: "所属账号",
          key: "userAccount",
          width: 160,
        },
        {
          title: "操作",
          align: "center",
          render: (h, params) => {
            let ifStatus;
            if (params.row.status == 0) {
              ifStatus = true;
            } else if (params.row.status == 1) {
              ifStatus = false;
            }
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    icon: "md-glasses",
                  },
                  style: {
                    id: "btn1",
                    marginLeft: "15px",
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                    },
                  },
                },
                "详情"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "info",
                    size: "small",
                    icon: "md-create",
                  },
                  style: {
                    marginLeft: "15px",
                  },
                  on: {
                    click: () => {
                      this.open2(params.index);
                    },
                  },
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                    icon: "ios-trash-outline",
                  },
                  style: {
                    marginLeft: "15px",
                  },
                  on: {
                    click: () => {
                      this.ifDelete(params.index);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
    };
  },
  created() {
    //页面加载时
    //查询员工
    this.selectEmp();
    //查询用户
    this.userList();
    this.$axios
      .get("/dept/ListTreeData")
      .then((result) => {
        this.data2 = result.data.data;
      })
      .catch((err) => {
        console.log(err);
      });
  },
  methods: {
    //弹出框点取消时
    cancel() {},
    //查询员工
    selectEmp() {
      this.loading = true;
      this.$axios
        .post("/emp/listPaged", this.empQo)
        .then((result) => {
          this.data = result.data.data;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取用户列表，以便搜索用户时选择
    userList() {
      this.$axios
        .get("/emp/listUsers", {
          params: {
            empId: null,
          },
        })
        .then((result) => {
          this.selectUser = result.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //点击清空下拉框按钮时触发
    handleClearDept() {
      this.empPO.deptId = null;
      this.deptName = "";
    },
    handleClearDept2() {
      this.deptName2 = "";
      this.empQo.deptId = null;
    },
    handleClearDept3() {
      this.empPO.deptName = "";
      this.empPO.deptId = null;
    },
    //点击清空下拉框按钮时触发
    handleClearUser() {
      this.empPO.userId = null;
    },
    //打开添加员工弹窗
    open() {
      this.$axios
        .get("/emp/listUsers", {
          params: {
            empId: null,
          },
        })
        .then((result) => {
          this.selectUser = result.data.data;
          this.deptName = "";
        })
        .catch((err) => {
          console.log(err);
        });
      this.$axios
        .get("/dept/ListTreeData")
        .then((result) => {
          this.data2 = result.data.data;
          this.modal1 = true;
        })
        .catch((err) => {
          console.log(err);
        });

      this.modal1 = true;
    },
    //打开修改员工弹窗
    open2(index) {
      this.$axios
        .get("/dept/ListTreeData", {
          params: {
            Id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.data2 = result.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
      this.$axios
        .get("/emp/listUsers", {
          params: {
            empId: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.selectUser = result.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
      this.$axios
        .get("/emp/selectEmpById", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.empPO = {};
          this.empPO = result.data.data;
          console.log(this.empPO);
          this.modal2 = true;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //添加员工
    addEmp(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的员工信息是否正确
        if (valid) {
          this.$axios
            .post("/emp/addEmp", this.empPO)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: "添加成功",
                });
                //插入数据成功更新查询
                this.selectEmp();
                //清空上次保存的员工信息
                this.empPO = {};
                this.deptName = "";
                this.userList();
                this.modal1 = false;
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "添加失败",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //改变页数时
    changePage(e) {
      //变更查询时的页数条件
      this.empQo.pageIndex = e;
      this.selectEmp();
    },
    //多选选中员工
    checkEmp(e) {
      //先将选中id设为空，以免重复添加id
      this.empIdList = [];
      console.log(e);
      //循环添加id
      e.forEach((element) => {
        this.empIdList.push(element.id);
      });
      console.log(this.empIdList);
    },

    //弹框问是否删除多选
    ifDeleteAll() {
      if (
        this.empIdList !== undefined &&
        this.empIdList !== null &&
        this.empIdList.length > 0
      ) {
        this.$Modal.confirm({
          title: "警告",
          content: "<p>你真的要删除这些员工么?</p>",
          onOk: () => {
            this.deleteCheckEmp();
          },
          onCancel: () => {},
        });
      } else {
        this.$Message.warning({
          top: 30,
          duration: 2.5,
          background: true,
          content: "您未选择任何员工",
        });
      }
    },
    //删除选中的员工
    deleteCheckEmp() {
      this.$axios
        .post("/emp/deleteCheckEmp", this.empIdList)
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectEmp();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //弹框问是否删除
    ifDelete(index) {
      this.$Modal.confirm({
        title: "警告",
        content: "<p>你真的要删除该员工么?</p>",
        onOk: () => {
          this.remove(index);
        },
        onCancel: () => {},
      });
    },
    //删除单个员工
    remove(index) {
      this.$axios
        .get("/emp/deleteEmp", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectEmp();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //员工详情信息
    show(index) {
      this.value4 = true;
      this.$axios
        .get("/emp/selectEmpById", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.details = result.data.data;
          console.log(this.details);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //修改员工信息
    updateEmp(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的员工信息是否正确
        if (valid) {
          this.$axios
            .post("/emp/updateEmp", this.empPO)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: "修改成功",
                });
                //插入数据成功更新查询
                this.selectEmp();
                //清空上次保存的员工信息
                this.empPO = {};
                this.modal2 = false;
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "修改失败",
                });
              }
              console.log(result.data);
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //关闭弹窗时，清除empPO信息
    cancel() {
      this.empPO = {};
    },
    //右键表格时得到右键表格的位置
    handleContextMenu(row) {
      const index = this.data.records.findIndex(
        (item) => item.name === row.name
      );
      this.contextLine = index;
    },
    //右键修改信息
    handleContextMenuEdit() {
      this.open2(this.contextLine);
    },
    //右键删除员工
    handleContextMenuDelete() {
      this.$Modal.confirm({
        title: "警告",
        content: "<p>你真的要删除该角色么?</p>",
        onOk: () => {
          this.remove(this.contextLine);
        },
        onCancel: () => {},
      });
    },
    //改变页面显示数据大小后
    sizeChange(e) {
      this.empQo.pageSize = e;
      this.selectEmp();
    },
    //清除查询条件
    reset() {
      (this.empQo = {
        pageSize: this.empQo.pageSize,
        pageIndex: 1,
      }),
        this.selectEmp();
    },
    //下拉框选中部门时
    handleNodeClick(data) {
      console.log(data);
      this.empPO.deptId = data.id;
      this.deptName = data.name;
      this.$refs.selectUpResId1.blur();
      console.log(this.empPO.deptName);
    },
    //下拉框选中部门时
    handleNodeClick2(data) {
      console.log(data);
      this.empPO.deptId = data.id;
      this.empPO.deptName = data.name;
      this.$refs.selectUpResId2.blur();
    },
    //下拉框选中部门时
    handleNodeClick3(data) {
      console.log(data);
      this.empQo.deptId = data.id;
      this.deptName2 = data.name;
      this.$refs.selectUpResId3.blur();
    },
  },
};
</script>